package org.jeecg.glr.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SysUtil;
import org.jeecg.glr.domain.glr.*;
import org.jeecg.glr.domain.led.DataDomain;
import org.jeecg.glr.entity.GlrGateway;
import org.jeecg.glr.entity.GlrPattern;
import org.jeecg.glr.service.IGateWayCommon;
import org.jeecg.glr.service.IGlrGatewayService;
import org.jeecg.glr.util.GLRConstant;
import org.jeecg.glr.util.ResponseMessage;
import org.jeecg.glr.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 网关管理
 * @Author: jeecg-boot
 * @Date:   2020-03-05
 * @Version: V1.0
 */
@RestController
@RequestMapping("/glr/glrGateway")
@Slf4j
public class GlrGatewayController extends JeecgController<GlrGateway, IGlrGatewayService> {
	@Autowired
	private IGlrGatewayService glrGatewayService;


     @Value("${glr.url.light_gateway_status}")
     private String light_gateway_status;
     @Value("${glr.url.light_gateway_get_data}")
     private String light_gateway_get_data;

	@Autowired
	private RedisUtil redisUtil;

     @Value("${glr.url.light_gateway_set_open_status}")
     private String light_gateway_set_open_status;

     @Resource
	 IGateWayCommon gateWayCommon;

	@Value(value = "${jeecg.path.upload}")
	private String uploadpath;



	/**
	 * 分页列表查询
	 *
	 * @param glrGateway
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@GetMapping(value = "/list")
	public Result<?> queryPageList(GlrGateway glrGateway,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<GlrGateway> queryWrapper = QueryGenerator.initQueryWrapperCode(glrGateway, req.getParameterMap());
		Page<GlrGateway> page = new Page<GlrGateway>(pageNo, pageSize);
		IPage<GlrGateway> pageList = glrGatewayService.page(page, queryWrapper);
		return Result.ok(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param glrGateway
	 * @return
	 */
	@AutoLog(value = "添加网关信息",logType= CommonConstant.LOG_TYPE_2)
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody GlrGateway glrGateway) {
		glrGatewayService.saveEntity(glrGateway);
		return Result.ok("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param glrGateway
	 * @return
	 */
	@AutoLog(value = "修改网关信息",logType= CommonConstant.LOG_TYPE_2)
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody GlrGateway glrGateway) {
		glrGatewayService.updateEntityById(glrGateway);
		return Result.ok("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "删除网关信息",logType= CommonConstant.LOG_TYPE_2)
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		glrGatewayService.removeEntityById(id);
		//redisUtil.delMap(GLRConstant.LIGHT_GATAWAY_CODE_REDIS);
		return Result.ok("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "删除网关信息",logType= CommonConstant.LOG_TYPE_2)
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.glrGatewayService.removeEntityByIds(Arrays.asList(ids.split(",")));
		return Result.ok("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		GlrGateway glrGateway = glrGatewayService.getById(id);
		if(glrGateway==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(glrGateway);
	}


     /**
      *   读取网关信息
      *
      * @param glrGateway
      * @return
      */
     @PostMapping(value = "/readGateWay")
     public Result<?> readGateWay(@RequestBody GlrGateway glrGateway) {
         String[] codes=glrGateway.getGateWayCodes().split(",");
         for(int i=0;i<codes.length;i++){
			 GataWayDomain gataWayDomain = new GataWayDomain();
			 gataWayDomain.setGateWayCode(codes[i]);
			 gateWayCommon.readGateWay(gataWayDomain);
         }
         return Result.ok("操作成功！");
     }

    /**
     *
     * 功能描述: 控制网关下的路灯开关
     *
     * @param: 
     * @return: 
     * @auther: Administrator
     * @date: 2020/3/9 9:32
     */
	@AutoLog(value = "群开、群关操作",logType= CommonConstant.LOG_TYPE_2)
     @PostMapping(value = "/ledOpenOrClose")
     public Result<?> ledOpenOrClose(@RequestBody GlrGateway glrGateway) {
		String[] codes=glrGateway.getGateWayCodes().split(",");
		for(int i=0;i<codes.length;i++){
			GlrGateWayControlLight lg = new GlrGateWayControlLight();
			lg.setGateWayCode(codes[i]);
			lg.setBrightValue(glrGateway.getBrightValue());
			lg.setType(GLRConstant.GLR_GATE_WAY_CONTROL_LIGHT_TYPE_03);
			gateWayCommon.ledOpenOrClose(lg);
		}
		return Result.ok("操作成功！");
     }
     
     /**
      *
      * 功能描述: 控制网关上电
      *
      * @param:
      * @return: 
      * @auther: Administrator
      * @date: 2020/3/9 9:33
      */
     @PostMapping(value = "/powerUpOrFailure")
     public Result<?> powerUpOrFailure(@RequestBody GlrGateway glrGateway) {
         String[] codes=glrGateway.getGateWayCodes().split(",");
         for(int i=0;i<codes.length;i++){
			 GlrGateWayOpenSatusDomain domain = new GlrGateWayOpenSatusDomain();
			 domain.setGateWayCode(codes[i]);
			 domain.setOpenstatusvalue(glrGateway.getSwitchingState());
			 gateWayCommon.setOpenStatus(domain);
         }
         return Result.ok("操作成功！");
     }

    /**
    * 导出excel
    *
    * @param request
    * @param glrGateway
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, GlrGateway glrGateway) {
        return super.exportXls(request, glrGateway, GlrGateway.class, "网关管理");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, GlrGateway.class);
    }

     /**
      *   读取网关信息
      *
      * @return
      */
     @PostMapping(value = "/getGateWay")
     public Result<?> getGateWay() {
        List<GlrGateway> gateList= glrGatewayService.getGlrGatewaySelect();
         return Result.ok(gateList);
     }

     /**
      *   修改经纬度
      *
      * @param glrGateway
      * @return
      */
     @PostMapping(value = "/updateLg")
     public Result<?> updateLg(@RequestBody GlrGateway glrGateway) {
         glrGatewayService.updateById(glrGateway);
         return Result.ok("操作成功");
     }

	 /**
	  *   读取网关信息
	  *
	  * @return
	  */
	 @PostMapping(value = "/readDate")
	 public Result<?> readDate(@RequestBody DateTimeDomain dateTimeDomain) {
		 ResponseMessage domain=gateWayCommon.readDate(dateTimeDomain);
	 	if(domain!=null){
			Calendar date = Calendar.getInstance();
			String year = String.valueOf(date.get(Calendar.YEAR));
			SimpleDateFormat sft = new SimpleDateFormat("yyyyMMddHHmmss");
			try
			{
				Date dt = sft.parse(year.substring(0, 2) + domain.getData().toString());
				SimpleDateFormat sftstr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				dateTimeDomain.setDateTime(sftstr.format(dt));
				return Result.ok(dateTimeDomain);
			}
			catch (ParseException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		 return Result.error("操作失败");
	 }


	 /**
	  *   设置网关时间
	  *
	  * @return
	  */
	 @PostMapping(value = "/setDate")
	 public Result<?> setDate(@RequestBody DateTimeDomain dateTimeDomain) {
		 Boolean flag=gateWayCommon.setDate(dateTimeDomain);
		 if(flag){
		 	return Result.ok("操作成功");
		 }
		 return Result.error("操作失败");
	 }

	 /**
	  *   读取分控网关
	  * @return
	  */
	 @PostMapping(value = "/readLightGateWay")
	 public Result<?> readLightGateWay(@RequestBody GataWayDomain gataWayDomain) {
		 ResponseMessage  domain=gateWayCommon.readLightGateWay(gataWayDomain);
		 if(domain!=null){
			return Result.ok(domain);
		 }
		 return Result.error("操作失败");
	 }





	 /**
	  *   设置分控地址
	  *
	  * @return
	  */
	 @PostMapping(value = "/setLightGateWay")
	 public Result<?> setLightGateWay(@RequestBody GlrGateWayLightGateWayDomain glrGateWayLightGateWayDomain) {
		 Boolean flag=gateWayCommon.setLightGateWay(glrGateWayLightGateWayDomain);
		 if(flag){
			 return Result.ok("操作成功");
		 }
		 return Result.error("操作失败");
	 }


	 /**
	  *   读取网关信息
	  * @return
	  */
	 @PostMapping(value = "/getOpenStatus")
	 public Result<?> getOpenStatus(@RequestBody GataWayDomain gataWayDomain) {
		 ResponseMessage domain=gateWayCommon.getOpenStatus(gataWayDomain);
		 if(domain!=null){
			 return Result.ok(domain);
		 }
		 return Result.error("操作失败");
	 }

	 /**
	  *   设置开关状态
	  *
	  * @return
	  */
	 @PostMapping(value = "/setOpenStatus")
	 public Result<?> setOpenStatus(@RequestBody GlrGateWayOpenSatusDomain glrGateWayOpenSatusDomain) {
		 Boolean flag=gateWayCommon.setOpenStatus(glrGateWayOpenSatusDomain);
		 if(flag){
			 return Result.ok("操作成功");
		 }
		 return Result.error("操作失败");
	 }

	 /**
	  *   获取IP
	  *
	  * @return
	  */
	 @PostMapping(value = "/getIP")
	 public Result<?> getIP(@RequestBody GlrIPDomain ipdomain) {
		 ResponseMessage domain=gateWayCommon.getIP(ipdomain);
		 if(domain!=null){
			 return Result.ok(domain);
		 }
		 return Result.error("操作失败");
	 }

	/**
	 *   设置IP
	 *
	 * @return
	 */
	@PostMapping(value = "/setIP")
	public Result<?> setIP(@RequestBody GlrIPDomain ipdomain) {
		Boolean flag=gateWayCommon.setIP(ipdomain);
		if(flag){
			return Result.ok("操作成功");
		}
		return Result.error("操作失败");
	}

	 /**
	  *   读取网关信息
	  *
	  * @return
	  */
	 @PostMapping(value = "/getGateWayMsg")
	 public Result<?> getGateWayMsg(@RequestBody GataWayDomain gataWayDomain) {
		 ResponseMessage domain=gateWayCommon.getGateWayMsg(gataWayDomain);
		 if(domain!=null){
			 return Result.ok(domain);
		 }
		 return Result.error("操作失败");
	 }
	 /**
	  *   设置开关状态
	  *
	  * @return
	  */
	 @PostMapping(value = "/setGateWayMsg")
	 public Result<?> setGateWayMsg(@RequestBody GlrGateWayMsgDomain domain) {
		 Boolean flag=gateWayCommon.setGateWayMsg(domain);
		 if(flag){
			 return Result.ok("操作成功");
		 }
		 return Result.error("操作失败");
	 }




	/**
	  *   获取测试结果
	  *
	  * @return
	  */
	 @PostMapping(value = "/getPacketLoss")
	 public Result<?> getPacketLoss(@RequestBody GataWayDomain gataWayDomain) {
		 ResponseMessage domain=gateWayCommon.getPacketLoss(gataWayDomain);
		 if(domain!=null){
			 return Result.ok(domain);
		 }
		 return Result.error("操作失败");
	 }

	 /**
	  *   测试信息
	  *
	  * @return
	  */
	 @PostMapping(value = "/setPacketLoss")
	 public Result<?> setPacketLoss(@RequestBody GlrGateWayTestDomain glrGateWayTestDomain) {
		 Boolean flag=gateWayCommon.setPacketLoss(glrGateWayTestDomain);
		 if(flag){
			 return Result.ok("操作成功");
		 }
		 return Result.error("操作失败");
	 }

	/**
	 *   设置开关状态
	 *
	 * @return
	 */
	@PostMapping(value = "/setTimeFrameAndDimming")
	public Result<?> setTimeFrameAndDimming(@RequestBody GlrGateWayPatternDomain glrGateWayPatternDomain) {

		/*
			String timeFrams = "";
			String luminances = "";
			timeFrams = pattern.getCommandTimea() + "," + pattern.getTypeb()+pattern.getCommandTimeb() + "," + pattern.getTypec()+pattern.getCommandTimec() + ","
					+ pattern.getCommandTimed() + "," + pattern.getCommandTimee();
			luminances = pattern.getBrightValuea() + "," + pattern.getBrightValueb() + "," + pattern.getBrightValuec() + ","
					+ pattern.getBrightValued() + "," + pattern.getBrightValuee();
			GlrGateWayPatternDomain domain = new GlrGateWayPatternDomain();
			domain.setGateWayCode(pattern.getGateWayCode());
			domain.setLuminance(luminances);
			domain.setTimeFrame(timeFrams.replace(":",""));
			*/
		//glrGateWayPatternDomain.setCommandTimea();

		glrGateWayPatternDomain.setCommandTimea(glrGateWayPatternDomain.getCommandTimea().replace(":",""));
		glrGateWayPatternDomain.setCommandTimeb(glrGateWayPatternDomain.getCommandTimeb().replace(":",""));
		glrGateWayPatternDomain.setCommandTimec(glrGateWayPatternDomain.getCommandTimec().replace(":",""));
		glrGateWayPatternDomain.setCommandTimed(glrGateWayPatternDomain.getCommandTimed().replace(":",""));
		glrGateWayPatternDomain.setCommandTimee(glrGateWayPatternDomain.getCommandTimee().replace(":",""));
			Boolean flag= gateWayCommon.setTimeFrameAndDimming(glrGateWayPatternDomain);
			if(flag){
				return Result.ok("操作成功！");
			}
			return Result.ok("操作失败！");
	}


	/**
	 *   读取模式
	 *
	 * @return
	 */
	@PostMapping(value = "/getTimeFrameAndDimming")
	public Result<?> getTimeFrameAndDimming(@RequestBody GataWayDomain gataWayDomain) {
		ResponseMessage domain=gateWayCommon.getTimeFrameAndDimming(gataWayDomain);
		if(domain!=null){
			return Result.ok(domain);
		}
		return Result.error("操作失败");
	}



	/**
	 *   设置开关状态
	 *
	 * @return
	 */
	@PostMapping(value = "/getGPS")
	public Result<?> getGPS(@RequestBody GlrGateWayGpsDomain gataWayDomain) {
		ResponseMessage domain=gateWayCommon.getGPS(gataWayDomain);
		if(domain!=null){
			return Result.ok(domain);
		}
		return Result.error("操作失败");
	}
	/**
	 *   设置开关状态
	 *
	 * @return
	 */
	@PostMapping(value = "/setGPS")
	public Result<?> setGPS(@RequestBody GlrGateWayGpsDomain glrGateWayGpsDomain) {
		Boolean flag=gateWayCommon.setGPS(glrGateWayGpsDomain);
		if(flag){
			return Result.ok("操作成功");
		}
		return Result.error("操作失败");
	}

	/**
	 *   设置开关状态
	 *
	 * @return
	 */
	@PostMapping(value = "/setIlluminance")
	public Result<?> setIlluminance(@RequestBody GlrGateIlluminanceDomain glrGateIlluminanceDomain) {
		Boolean flag=gateWayCommon.setIlluminance(glrGateIlluminanceDomain);
		if(flag){
			return Result.ok("操作成功");
		}
		return Result.error("操作失败");
	}

	/**
	 *   设置开关状态
	 *
	 * @return
	 */
	@PostMapping(value = "/getIlluminance")
	public Result<?> getIlluminance(@RequestBody GataWayDomain gataWayDomain) {
		ResponseMessage domain=gateWayCommon.getIlluminance(gataWayDomain);
		if(domain!=null){
			return Result.ok(domain);
		}
		return Result.error("操作失败");
	}

    /**
     *   设置厂家设定
     *
     * @return
     */
    @PostMapping(value = "/setManufacturerSet")
    public Result<?> setManufacturerSet(@RequestBody GlrGateWayManufacturerSetDomain glrGateWayManufacturerSetDomain) {
        Boolean flag=gateWayCommon.setManufacturerSet(glrGateWayManufacturerSetDomain);
        if(flag){
            return Result.ok("操作成功");
        }
        return Result.error("操作失败");
    }

    /**
     *   读取厂家设定
     *
     * @return
     */
    @PostMapping(value = "/getManufacturerSet")
    public Result<?> getManufacturerSet(@RequestBody GataWayDomain gataWayDomain) {
        ResponseMessage domain=gateWayCommon.getManufacturerSet(gataWayDomain);
        if(domain!=null){
            return Result.ok(domain);
        }
        return Result.error("操作失败");
    }

    /**
     *   设置额定功率
     *
     * @return
     */
    @PostMapping(value = "/setRatedPower")
    public Result<?> setRatedPower(@RequestBody GlrGateWayRatedPowerDomain glrGateWayRatedPowerDomain) {
        Boolean flag=gateWayCommon.setRatedPower(glrGateWayRatedPowerDomain);
        if(flag){
            return Result.ok("操作成功");
        }
        return Result.error("操作失败");
    }

    /**
     *   读取额定功率
     *
     * @return
     */
    @PostMapping(value = "/getRatedPower")
    public Result<?> getRatedPower(@RequestBody GataWayDomain gataWayDomain) {
        ResponseMessage domain=gateWayCommon.getRatedPower(gataWayDomain);
        if(domain!=null){
            return Result.ok(domain);
        }
        return Result.error("操作失败");
    }

	/**
	 *   设置分控MAC
	 *
	 * @return
	 */
	@PostMapping(value = "/setSubControlMAC")
	public Result<?> setSubControlMAC(@RequestBody GlrGateWaySubControlMACDomain glrGateWaySubControlMACDomain) {
		Boolean flag=gateWayCommon.setSubControlMAC(glrGateWaySubControlMACDomain);
		if(flag){
			return Result.ok("操作成功");
		}
		return Result.error("操作失败");
	}

	/**
	 *   读取分控MAC
	 *
	 * @return
	 */
	@PostMapping(value = "/getSubControlMAC")
	public Result<?> getSubControlMAC(@RequestBody GataWayDomain gataWayDomain) {
		ResponseMessage domain=gateWayCommon.getSubControlMAC(gataWayDomain);
		if(domain!=null){
			return Result.ok(domain);
		}
		return Result.error("操作失败");
	}


	/**
	 *    读号版本号
	 *
	 * @return
	 */
	@PostMapping(value = "/getVersionNo")
	public Result<?> getVersionNo(@RequestBody GataWayDomain gataWayDomain) {
		ResponseMessage domain=gateWayCommon.getVersionNo(gataWayDomain);
		if(domain!=null){
			return Result.ok(domain);
		}
		return Result.error("操作失败");
	}


	/**
	 *   设置系统重启
	 *
	 * @return
	 */
	@PostMapping(value = "/setSystemRestart")
	public Result<?> setSystemRestart(@RequestBody GlrGateWaySystemRestartDomain glrGateWaySystemRestartDomain) {
		Boolean flag=gateWayCommon.setSystemRestart(glrGateWaySystemRestartDomain);
		if(flag){
			return Result.ok("操作成功");
		}
		return Result.error("操作失败");
	}


	/**
	 *   设置分控地址
	 *
	 * @return
	 */
	@PostMapping(value = "/readLightAddress")
	public Result<?> readLightAddress(@RequestBody GataWayDomain gataWayDomain) {
		ResponseMessage domain=gateWayCommon.readLightAddress(gataWayDomain);
		if(domain!=null){
			if(StringUtil.isNotEmpty(domain.getData())){
				List<String> list = new ArrayList<String>();
				String regex = "(.{4})";
				String value = domain.getData().toString().replaceAll(regex, "$1,");
				String[] valstr = value.split(",");
				for (int i = 0; i < valstr.length; i++)
				{
					list.add(valstr[i]);
				}

				int ilen=255;
				if (ilen-list.size()>0) {
					int ilenOther = ilen - list.size();
					for (int i = 0; i < ilenOther; i++){
						list.add("");
					}
				}
				domain.setData(list);
			}
			return Result.ok(domain);
		}
		return Result.error("操作失败");
	}

	/**
	 *   写入分控地址
	 *
	 * @return
	 */
	@PostMapping(value = "/setLightAddress")
	public Result<?> setLightAddress(@RequestBody GlrLightGateAddressDomain glrLightGateAddressDomain) {
		Boolean flag=gateWayCommon.setLightAddress(glrLightGateAddressDomain);
		if(flag){
			return Result.ok("操作成功");
		}
		return Result.error("操作失败");
	}

	/**
	 *   设置相位
	 *
	 * @return
	 */
	@PostMapping(value = "/readLightPhase")
	public Result<?> readLightPhase(@RequestBody GataWayDomain gataWayDomain) {
		ResponseMessage domain=gateWayCommon.readLightPhase(gataWayDomain);
		if(domain!=null){
			if(StringUtil.isNotEmpty(domain.getData())){

				Map map=(Map)domain.getData();
				String stV1=map.get("v1").toString();
				String stV2=map.get("v2").toString();
				int ilen=255;

				Map<String,Object> map1=new HashMap<>();
				String[] valstr1 = stV1.split(",");
				String[] valstr2 = stV2.split(",");
				List<String> list1 = new ArrayList<String>();
				List<String> list2= new ArrayList<String>();

				for (int i = 0; i < valstr1.length; i++)
				{
					list1.add(valstr1[i]);
				}

				if (ilen-list1.size()>0) {
					int ilenOther = ilen - list1.size();
					for (int i = 0; i < ilenOther; i++){
						list1.add("");
					}
				}
				for (int i = 0; i < valstr2.length; i++)
				{
					list2.add(valstr2[i]);
				}

				if (ilen-list2.size()>0) {
					int ilenOther = ilen - list2.size();
					for (int i = 0; i < ilenOther; i++){
						list2.add("");
					}
				}

				map1.put("v1",list1);
				map1.put("v2",list2);

				domain.setData(map1);

			}
			return Result.ok(domain);
		}
		return Result.error("操作失败");
	}

	/**
	 *   写入相位
	 *
	 * @return
	 */
	@PostMapping(value = "/setLightPhase")
	public Result<?> setLightPhase(@RequestBody GlrLightGatePhaseDomain glrLightGatePhaseDomain) {
		Boolean flag=gateWayCommon.setLightPhase(glrLightGatePhaseDomain);
		if(flag){
			return Result.ok("操作成功");
		}
		return Result.error("操作失败");
	}


	/**
	 *   设置功率
	 *
	 * @return
	 */
	@PostMapping(value = "/readLightRatedPower")
	public Result<?> readLightRatedPower(@RequestBody GataWayDomain gataWayDomain) {
		ResponseMessage domain=gateWayCommon.readLightRatedPower(gataWayDomain);
		if(domain!=null){
			if(StringUtil.isNotEmpty(domain.getData())){
				List<String> list = new ArrayList<String>();
				String[] valstr = domain.getData().toString().split(",");
				for (int i = 0; i < valstr.length; i++)
				{
					list.add(valstr[i]);
				}

				int ilen=255;
				if (ilen-list.size()>0) {
					int ilenOther = ilen - list.size();
					for (int i = 0; i < ilenOther; i++){
						list.add("");
					}
				}
				domain.setData(list);
			}
			return Result.ok(domain);
		}else{
			List<String> list = new ArrayList<String>();
			int ilen=255;
			if (ilen-list.size()>0) {
				int ilenOther = ilen - list.size();
				for (int i = 0; i < ilenOther; i++){
					list.add("");
				}
			}
			domain=new ResponseMessage();
			domain.setData(list);
			return Result.ok(domain);
		}
	}

	/**
	 *   写入功率
	 *
	 * @return
	 */
	@PostMapping(value = "/setLightRatedPower")
	public Result<?> setLightRatedPower(@RequestBody GlrLightGateRatedPowerDomain glrLightGateRatedPowerDomain) {
		Boolean flag=gateWayCommon.setLightRatedPower(glrLightGateRatedPowerDomain);
		if(flag){
			return Result.ok("操作成功");
		}
		return Result.error("操作失败");
	}

	/**
	 *   固件更新
	 *
	 * @return
	 */
	@PostMapping(value = "/setFirmwareUpdate")
	public Result<?> setFirmwareUpdate(@RequestBody GlrLightGateFirmwareUpdateDomain glrLightGateFirmwareUpdateDomain) {
		String uploadFilaName=glrLightGateFirmwareUpdateDomain.getUploadFilaName();
		String[] filenames=uploadFilaName.split("#");
		if (filenames.length>0){
			String filePath=uploadpath+ File.separator +filenames[0];
			byte[] buffer = null;
			File file = new File(filePath);
			FileInputStream fis;
			try {
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				fis = new FileInputStream(file);
				byte[] b = new byte[1024];
				int n;
				while ((n = fis.read(b)) != -1) {
					bos.write(b, 0, n);
				}
				fis.close();
				bos.close();
				buffer = bos.toByteArray();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}catch (IOException e) {
				e.printStackTrace();
			}
			glrLightGateFirmwareUpdateDomain.setByteFile(buffer);
		}

		Boolean flag=gateWayCommon.setFirmwareUpdate(glrLightGateFirmwareUpdateDomain);
		if(flag){
			return Result.ok("操作成功");
		}
		return Result.error("操作失败");
	}



	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importLightAddress", method = RequestMethod.POST)
	public Result<?> importLightAddress(HttpServletRequest request, HttpServletResponse response) {
		//System.out.println(request.getParameter("gateWayCode")+"--------------");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(1);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				String address="";
				List<GlrLightGateAddressDomain> list = ExcelImportUtil.importExcel(file.getInputStream(), GlrLightGateAddressDomain.class, params);
				for (GlrLightGateAddressDomain domain :
						list) {
					if(StringUtil.isNotEmpty(domain.getAddress())){
						if(StringUtil.isEmpty(address)){
							address=domain.getAddress();
						}else{
							address=address+","+domain.getAddress();
						}
					}

				}
				GlrLightGateAddressDomain glrdomain = new GlrLightGateAddressDomain();
				glrdomain.setAddress(address);
				glrdomain.setGateWayCode(request.getParameter("gateWayCode"));
				gateWayCommon.setLightAddress(glrdomain);
				return Result.ok("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}

	/**
	 * 通过excel导入功率数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importLightRatedPower", method = RequestMethod.POST)
	public Result<?> importLightRatedPower(HttpServletRequest request, HttpServletResponse response) {
		//System.out.println(request.getParameter("gateWayCode")+"--------------");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(1);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				String address="";
				List<GlrLightGateRatedPowerDomain> list = ExcelImportUtil.importExcel(file.getInputStream(), GlrLightGateRatedPowerDomain.class, params);
				for (GlrLightGateRatedPowerDomain domain :
						list) {
					if(StringUtil.isNotEmpty(domain.getLightPower())){
						if(StringUtil.isEmpty(address)){
							address=domain.getLightPower();
						}else{
							address=address+","+domain.getLightPower();
						}
					}

				}
				GlrLightGateRatedPowerDomain glrdomain = new GlrLightGateRatedPowerDomain();
				glrdomain.setLightPower(address);
				glrdomain.setGateWayCode(request.getParameter("gateWayCode"));
				gateWayCommon.setLightRatedPower(glrdomain);
				return Result.ok("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}

}
